<template>
    <div class="account_person_open">
        <accountSteps :activeStep="Data.activeStep"></accountSteps>
        <div class="container_information" v-if="Data.activeStep == 0">
            <el-form :rules="rules" ref="infoRef" :model="infoData" label-width="auto">
                <el-form-item label="身份证人像面" prop="sfzr">
                    <div class="img_block">
                        <UploadImg v-model:imageUrl="infoData.sfzr" :fileSize="2" tip="(JPG，JPEG，PNG不超过2M)" />
                    </div>
                </el-form-item>
                <el-form-item label="身份证国徽面" prop="sfzg">
                    <div class="img_block">
                        <UploadImg v-model:imageUrl="infoData.sfzg" :fileSize="2" tip="(JPG，JPEG，PNG不超过2M)" />
                    </div>
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="infoData.name" :maxlength="20" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="身份证号" prop="idNo">
                    <el-input v-model="infoData.idNo" :maxlength="20" show-word-limit></el-input>
                </el-form-item>
            </el-form>
            <div class="bottom_btn">
                <div class="btn" @click="submitInfoHandler">提交开户资料</div>
            </div>
        </div>
        <div class="container_card" v-if="Data.activeStep == 1">
            <el-form :rules="rules" ref="cardRef" :model="cardData" label-width="auto">
                <el-form-item label="银行卡号" prop="yhkh">
                    <el-input v-model.trim="cardData.yhkh" @blur="bankNoCheckHandler"></el-input>
                </el-form-item>
                <el-form-item label="开户银行" prop="khyh">
                    <el-input v-model="cardData.khyh"></el-input>
                </el-form-item>
                <el-form-item label="银行预留手机号" prop="phone">
                    <el-input v-model="cardData.phone" :maxlength="11"></el-input>
                </el-form-item>
                <el-form-item v-if="cardData.bankId !== 'CMB'" label="验证码" prop="yzm">
                    <el-input v-model="cardData.yzm">
                        <template #suffix>
                            <el-divider direction="vertical" />
                            <div
                                :class="cardData.smsText == '获取验证码' ? 'yzm_btn' : 'yzm_btn_wait'"
                                @click="verifiCode">
                                {{ cardData.smsText }}
                            </div>
                        </template>
                    </el-input>
                </el-form-item>
            </el-form>
            <div class="bottom_btn">
                <div class="btn" @click="submitCardHandler">确认绑卡</div>
            </div>
            <!-- 绑定账户 -->
            <BindAccountDialog ref="bindRef" @handle-confirm="backHandler" :btnVisible="false"> </BindAccountDialog>
        </div>
        <div class="container_success" v-if="Data.activeStep == 2">
            <div>
                <div class="img"><img src="@/assets/imgs/sys/verify-success.png" alt="" /></div>
                <div class="title">账户开通成功</div>
            </div>
            <div class="bottom_btn">
                <div class="btn" @click="backHandler">返回</div>
            </div>
        </div>

        <!-- 点击获取验证码弹窗 -->
        <el-dialog v-model="dialog.verification" width="30%">
            <div class="dialog_verifi">
                <div>系统已发送短信至您的手机，</div>
                <div>请点击短信链接进行绑卡&emsp;&emsp;</div>
                <div class="sure_btn" @click="successHandler">我已点击短信完成绑卡</div>
                <div class="dialog_tip">
                    短信已失效，<span class="re_btn" @click="reSendNessage">重新获取短信</span>
                </div>
            </div>
        </el-dialog>
    </div>
</template>
<script setup>
import { ref, reactive, onMounted, onUnmounted, computed, watch } from 'vue';
import accountSteps from './steps.vue';
import UploadImg from '@/components/UploadImg.vue';
import { useRouter, useRoute } from 'vue-router';
import { format, getRegExp, isMobile } from '@/commons/utils';
import request from '../../../../request';
import { ElMessageBox, ElMessage } from 'element-plus';
import BindAccountDialog from '../account/bindAccountDialog.vue';

const router = useRouter();
const route = useRoute();
const Data = reactive({
    // 初始步骤
    activeStep: Number(route.query.step) || 0,
    loginNo: '',
    paySequenceNo: ''
});
const infoData = reactive({
    sfzr: '',
    sfzg: '',
    name: '',
    idNo: ''
});
const cardData = reactive({
    yhkh: '',
    khyh: '',
    phone: '',
    yzm: '',
    bankId: '',
    smsText: '获取验证码'
});
/**
 * 校验手机号
 * @param {*} rule
 * @param {*} value
 * @param {*} callback
 */
const validatePhone = (rule, value, callback) => {
    if (isMobile(value)) {
        callback();
    } else {
        callback(new Error('请输入正确的手机号!'));
    }
};
const rules = reactive({
    sfzr: [{ required: true, message: '请上传身份证人像面照片', trigger: ['change', 'blur'] }],
    sfzg: [{ required: true, message: '请上传身份证国徽面照片', trigger: ['change', 'blur'] }],
    name: [{ required: true, message: '请输入姓名', trigger: ['change', 'blur'] }],
    idNo: [
        { required: true, message: '请输入身份证号', trigger: ['change', 'blur'] },
        {
            pattern: getRegExp('idcard'),
            message: '身份证号格式不正确',
            trigger: 'blur'
        }
    ],
    yhkh: [{ required: true, message: '请输入银行卡号', trigger: ['change', 'blur'] }],
    khyh: [{ required: true, message: '请输入开户银行', trigger: ['change', 'blur'] }],
    phone: [
        { required: true, message: '请输入银行预留手机号', trigger: ['change', 'blur'] },
        { validator: validatePhone, trigger: 'blur' }
    ],
    yzm: [{ required: true, message: '请输入验证码', trigger: 'change' }]
});

const dialog = reactive({
    verification: false
});

watch(
    () => infoData.sfzr,
    () => {
        if (infoData.sfzr && infoData.sfzg) {
            getInfoByIdCardImg();
        }
    }
);

watch(
    () => infoData.sfzg,
    () => {
        if (infoData.sfzr && infoData.sfzg) {
            getInfoByIdCardImg();
        }
    }
);

// 提交开户资料
const infoRef = ref();
const bindRef = ref();
const submitInfoHandler = () => {
    infoRef.value.validate(async valid => {
        if (valid) {
            const resp = await request('personalOpenServ', {
                name: infoData.name,
                IdNo: infoData.idNo,
                IdNationalEmblem: infoData.sfzg,
                IdPortrait: infoData.sfzr
            });
            if (resp.code === 0) {
                Data.activeStep = 1;
                Data.loginNo = resp.data.loginNo;
                Data.paySequenceNo = resp.data.paySequenceNo;
                Data.activeStep = 1;
            } else if (resp.code === 202304141725) {
                // 已开通过
                ElMessageBox.confirm('该身份证已经开过户，请直接绑定账户', '提示', {
                    confirmButtonText: '绑定账户',
                    cancelButtonText: '下次再说',
                    center: true,
                    type: 'none'
                })
                    .then(() => {
                        bindRef?.value?.handleOpen();
                    })
                    .catch(() => {});
            } else {
                const message = `${resp.msg || resp.data?.message || resp.data?.msg || '系统异常'}`;
                ElMessage.error(message);
            }
        }
    });
};

// 绑卡
const cardRef = ref();
const submitCardHandler = () => {
    cardRef.value.validate(async valid => {
        if (valid) {
            // 招行卡需要在外部绑卡
            if (cardData.bankId === 'CMB') {
                await request('bindCardServ', {
                    pageUrl: 'https://home.shop.keyid.cn/',
                    bankName: cardData.khyh, //开户名称
                    bankAccount: cardData.yhkh, //银行卡号
                    userMobile: cardData.phone, //联系人手机号
                    loginNo: Data.loginNo,
                    paySequenceNo: Data.paySequenceNo,
                    cardBin: 'CMB'
                });
                dialog.verification = true;
            } else {
                // 非招行卡直接绑卡
                await request('bindCardServ', {
                    // 可以不要
                    pageUrl: 'https://home.shop.keyid.cn/',
                    loginNo: Data.loginNo,
                    paySequenceNo: Data.paySequenceNo,
                    cardBin: cardData.bankId,
                    bankName: cardData.khyh, //开户名称
                    bankAccount: cardData.yhkh, //银行卡号
                    userMobile: cardData.phone, //联系人手机号
                    verifyCode: cardData.yzm //短信验证码
                });
                Data.activeStep = 2;
            }
        }
    });
};

// 返回
const backHandler = () => {
    router.back();
};

// ocr识别
const getInfoByIdCardImg = async () => {
    const idNationalEmblem = infoData.sfzg;
    const idPortrait = infoData.sfzr;
    const { data } = await request('queryIdcardServ', {
        idNationalEmblem,
        idPortrait
    });
    if (data.name || data.idNumber) {
        infoData.name = data.name;
        infoData.idNo = data.idNumber;
    }
};

// 卡宾
const bankNoCheckHandler = async () => {
    if (!cardData.yhkh) {
        return;
    }
    const { data } = await request('identifyBankCardServ', { cardNo: cardData.yhkh });
    cardData.khyh = data?.bankDescription;
    cardData.bankId = data?.bankId;
};

// 点击获取验证码
const verifiCode = () => {
    if (cardData.smsText !== '获取验证码') {
        return;
    }
    cardRef.value.validateField('phone', valid => {
        valid &&
            cardRef.value.validateField('yhkh', async v => {
                if (v) {
                    // 待办：补充发送验证码参数
                    await request('sendAccountSmsCodeServ', {
                        bankAccount: cardData.yhkh, //银行卡卡号
                        userMobile: cardData.phone, //手机号
                        cardBin: cardData.bankId, //银行卡卡bin
                        bankName: cardData.khyh,
                        loginNo: Data.loginNo,
                        paySequenceNo: Data.paySequenceNo
                    });
                    let count = 60; // 总倒计时秒数
                    const timer = setInterval(function () {
                        count--;
                        cardData.smsText = count;
                        if (count <= 0) {
                            clearInterval(timer); // 清除定时器
                            cardData.smsText = '获取验证码';
                        }
                    }, 1000); // 每秒执行一次
                }
            });
    });
};

// 待办：需要跳回列表页面
// 招行卡完成绑定
const successHandler = () => {
    router.back();
};

// 重发短信
const reSendNessage = async () => {
    await request('bindCardServ', {
        pageUrl: 'https://home.shop.keyid.cn/',
        bankName: cardData.khyh, //开户名称
        bankAccount: cardData.yhkh, //银行卡号
        userMobile: cardData.phone, //联系人手机号
        verifyCode: cardData.yzm, //短信验证码
        cardBin: 'CMB',
        loginNo: Data.loginNo,
        paySequenceNo: Data.paySequenceNo
    });
    ElMessage({
        type: 'success',
        message: '短信已发送~'
    });
};

onMounted(async () => {
    if (route.query.no && route.query.paySequenceNo) {
        Data.activeStep = 1;
        Data.loginNo = route.query.no;
        Data.paySequenceNo = route.query.paySequenceNo;
        const { data } = await request('queryBindCardInfoServ', {
            loginNo: route.query.no,
            paySequenceNo: route.query.paySequenceNo
        });
        cardData.yhkh = data.bankAccount;
        cardData.khyh = data.bankName;
        cardData.phone = data.userMobile;
        cardData.bankId = data.cardBin;
        if (data.cardBin == 'CMB' && data.msgCode == 1) {
            dialog.verification = true;
        }
    }
});
</script>
<style lang="scss" src="./open.scss" scoped></style>
